<template>
  <div id="login">

    <AppHeader />

    <el-container>
      <el-main>
        <div>
          <div style="margin-top: 10px; height: 100px;line-height: 100px;font-size: 40px;">欢迎来到xxx商城管理系统，请登录OwO</div>
          <div id="logininfo">
            <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
              <el-form-item label="账户名" prop="name">
                <el-input v-model="ruleForm.name" style="height: 50px; width: 495px;"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="ruleForm.phone" style="height: 50px; width: 495px;"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password" style="margin-top: 40px;">
                <el-input v-model="ruleForm.password" type="password" style="height: 50px; width: 495px;"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="passwords" style="margin-top: 40px;">
                <el-input v-model="ruleForm.passwords" type="password" style="height: 50px; width: 495px;"></el-input>
              </el-form-item>

              <el-form-item label="选择日期" prop="date" style="margin-top: 20px;">
                <el-date-picker v-model="ruleForm.date" type="date" placeholder="选择日期" style="width: 150px;"
                  :picker-options="pickerOptions"></el-date-picker>

                <div style="margin-left: 20px;">
                  <el-radio v-model="ruleForm.gender" label="1">男</el-radio>
                  <el-radio v-model="ruleForm.gender" label="2">女</el-radio>
                </div>
              </el-form-item>

              <!-- 省市区三级联动 -->
              <el-form-item label="所在地区" style="margin-top: 20px;">
                <!-- 选择省份 -->
                <el-select v-model="selectedProvinceId" placeholder="请选择省份" @change="handleProvinceChange"
                  style="width: 150px; margin-right: 10px;" clearable>
                  <el-option v-for="prov in provinces" :key="prov.districtId" :label="prov.district"
                    :value="prov.districtId" />
                </el-select>

                <!-- 选择城市 -->
                <el-select v-model="selectedCityId" placeholder="请选择城市" @change="handleCityChange"
                  style="width: 150px; margin-right: 10px;" :disabled="!selectedProvince" clearable>
                  <el-option v-for="city in cities" :key="city.districtId" :label="city.district"
                    :value="city.districtId" />
                </el-select>

                <!-- 选择区县 -->
                <el-select v-model="selectedDistrictId" placeholder="请选择区县" style="width: 150px;"
                  :disabled="!selectedCity" clearable>
                  <el-option v-for="dist in districts" :key="dist.districtId" :label="dist.district"
                    :value="dist.districtId" />
                </el-select>
              </el-form-item>

              <!-- 验证码部分 -->
              <el-form-item label="验证码" prop="code" style="margin-top: 40px;">
                <el-input v-model="ruleForm.code" style="height: 50px; width: 300px;" placeholder="请输入验证码"></el-input>

                <!-- 验证码图片 -->
                <img v-if="showRealCaptcha" :src="captchaImage" @click="refreshCaptcha" alt="验证码"
                  style="height: 50px; margin-left: 10px; cursor: pointer;">
                <div v-else style="display: inline-block; margin-left: 10px;">
                  <img style="height: 50px;" alt="验证码加载中...">
                  <span class="loading-text">{{ captchaLoading ? '...' : '点击刷新验证码' }}</span>
                </div>
              </el-form-item>

              <el-form-item style="margin-top: 70px;">
                <el-button type="primary" @click="submitForm(ruleFormRef)">立即注册</el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                <el-button style="margin: 0px 0px 0px 250px;" type="primary" @click="backlogin()">返回登录</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- <footer id="footer"></footer> -->
  </div>
</template>

<script setup>
//组件
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import api from "@/api/api"//调用封装后的api
import AppHeader from '@/components/Header/AppHeader.vue'//引入头部组件

const router = useRouter()

// Refs for form and state
const ruleFormRef = ref(null)
const loading = ref(false)//添加加载状态
const captchaLoading = ref(false)//加载验证码状态
const showRealCaptcha = ref(false)//显示真实验证码
const captchaImage = ref('')//存储真实验证码图片
const captchaToken = ref('')//存储验证码token
const verifCode = ref('')//存储验证码文本

// Form data  表单数据对象
const ruleForm = ref({
  name: '',
  phone: '',
  password: '',
  passwords: '',
  date: '',
  gender: '1',//默认男性
  code: '',
  province: '',
  city: '',
  district: ''
})

// Validation rules 密码验证规则
const passwordsValidator = (rule, value, callback) => {
  if (value !== ruleForm.value.password) {
    callback(new Error('两次输入的密码不一致，请重新输入'))
  } else {
    callback()
  }
}

const phoneValidator = (rule, value, callback) => {
  if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

const rules = {
  // 用户名
  name: [
    { required: true, message: '请输入账户名', trigger: 'blur' },
    { min: 3, max: 16, message: '长度在 3 到 5 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  // 手机号
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '长度在11个字符', trigger: 'blur' },
    { validator: phoneValidator, trigger: 'blur' }
  ],
  // 密码
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,18}$/, message: '需包含大小写字母和数字', trigger: 'blur' }
  ],
  // 确认密码
  passwords: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { min: 6, max: 18, trigger: 'blur', validator: passwordsValidator }
  ],
  //出生日期
  date: [
    { required: true, message: '请选择您出生的日期', trigger: 'change' }
  ],
  //验证码
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度为4-6位', trigger: 'blur' }
  ]
}

// Date picker options 日期选择器选项
const pickerOptions = {
  disabledDate(time) {
    return time.getTime() > Date.now()
  },
  shortcuts: [{
    text: '今天',
    onClick(picker) {
      picker.$emit('pick', new Date())
    }
  }, {
    text: '昨天',
    onClick(picker) {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      picker.$emit('pick', date)
    }
  }]
}

// 地区联动数据
// const regionData = {
// }

const provinces = ref([])
const cities = ref([])
const districts = ref([])

const selectedProvinceId = ref(null)
const selectedCityId = ref(null)
const selectedDistrictId = ref(null)

// 用 computed 计算选中的对象（用于访问 district、level 等）
const selectedProvince = computed(() =>
  provinces.value.find(p => p.districtId === selectedProvinceId.value)
)

const selectedCity = computed(() =>
  cities.value.find(c => c.districtId === selectedCityId.value)
)
const selectedDistrict = computed(() => {
  return districts.value.find(d => d.districtId === selectedDistrictId.value)
})


//  获取省份数据
onMounted(async () => {
  try {
    const response = await api.get('/regions/provinces')
    // console.log('获取后端省份数据:', response.data)
    provinces.value = response.data
    // console.log('传给前端省份数据:', provinces)
  } catch (error) {
    // console.error('获取省份数据失败:', error)
  }
})

// 获取城市数据
const handleProvinceChange = async () => {
  selectedCityId.value = null
  selectedDistrict.value = null
  cities.value = []
  districts.value = []

  if (selectedProvinceId.value != null) {
    try {
      // console.log('当前选择的省份:', selectedProvinceId)
      const response = await api.get('/regions/cities', {
        params: {
          district_id: selectedProvinceId.value,
          level: 2
        }
      })
      cities.value = response.data
      console.log(cities.value)
    } catch (error) {
      console.error('获取城市数据失败:', error)
    }
  }
}

// 获取区县数据
const handleCityChange = async () => {
  selectedDistrictId.value = null
  districts.value = []

  if (selectedCityId.value != null) {
    try {
      const response = await api.get('/regions/districts', {
        params: {
          district_id: selectedCityId.value,
          level: 3
        }
      })
      districts.value = response.data
    } catch (error) {
      console.error('获取区县数据失败:', error)
    }
  }
}


// Methods  获取图形验证码
const adjustFooter = () => {
  const loginDiv = document.getElementById('login')
  const windowHeight = window.innerHeight
  loginDiv.style.minHeight = `${windowHeight}px`
}

const refreshCaptcha = async () => {
  try {
    captchaLoading.value = true//开始加载验证码
    showRealCaptcha.value = false//隐藏真实验证码

    // Simulate API delay  模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500))

    const response = await api.get('user/verificationCode')//验证码api接口
    captchaImage.value = response.data.codeImg//设置验证码图片
    verifCode.value = response.data.verifiCode//储存验证码文本
    captchaToken.value = response.data.token || ''//设置验证码token
    showRealCaptcha.value = true//显示真实验证码

    ElMessage.success('验证码已刷新')
  } catch (error) {
    console.error('获取验证码失败', error)
    ElMessage.error('获取验证码失败，请稍后重试')
    showRealCaptcha.value = true
  } finally {
    captchaLoading.value = false//结束加载验证码
  }
}

const submitForm = async (formEl) => {
  if (!formEl) return

  try {
    const valid = await formEl.validate()
    if (!valid) {
      ElMessage.warning('请正确填写表单')
      return
    }

    // Check verification code 验证验证码是否正确
    if (ruleForm.value.code !== verifCode.value) {
      ElMessage.error('验证码错误，请重新输入')
      refreshCaptcha()//刷新验证码
      return
    }

    loading.value = true


    //获取注册时间
    const formatDate = (date) => {
      // 1. 获取本地时间偏移量（分钟），中国时区是 UTC+8，即 -480 分钟
      const timezoneOffset = date.getTimezoneOffset(); // 返回的是与 UTC 的分钟差，中国是 -480
      // 2. 调整时间到中国时区（UTC+8）
      const chinaOffset = 8 * 60; // 8 小时的分钟数
      const adjustedDate = new Date(date.getTime() + (timezoneOffset + chinaOffset) * 60 * 1000);
      // 3. 返回格式化的时间字符串
      return adjustedDate.toISOString().replace('T', ' ').substring(0, 19);
    }

    //测试提交

    // 示例：
    const date = new Date(); // 当前时间
    formatDate(date); // 输出：2025-05-23 12:34:56（中国时间）

    //发送给后端的数据
    const formData = {
      name: ruleForm.value.name,
      phone: ruleForm.value.phone,
      password: ruleForm.value.password,
      birthday: ruleForm.value.date,
      gender: parseInt(ruleForm.value.gender),
      verificationCode: ruleForm.value.code,
      token: captchaToken.value,
      province: selectedProvince.value.district,
      city: selectedCity.value.district,
      district: selectedDistrict.value.district,
      registerTime: date.toISOString(),//注册时间
    }
    //发送post请求
    const response = await api.post('/user/register', formData)

    if (response.data.code === 20200) {
      ElMessage.success('注册成功！')
      router.push({
        path: '/',
        query: { name: ruleForm.value.name }
      })
    } else {
      ElMessage.error(response.data.message || '注册失败')
    }
  } catch (error) {
    console.error('注册错误', error)
    let errorMessage = '注册失败，请重试'

    if (error.response) {
      errorMessage = `注册失败: ${error.response.data.message}`
    }
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false//结束加载
  }
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  ruleForm.value.gender = '1'//重置后恢复默认男性
}

const backlogin = () => {
  router.push('/')
}

// Lifecycle hooks
onMounted(() => {
  adjustFooter()
  window.addEventListener('resize', adjustFooter)
  showRealCaptcha.value = false
  refreshCaptcha()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', adjustFooter)
})
</script>

<style scoped>
#header,
#footer {
  height: 100px;
  background-color: rgb(255, 174, 0);
}

#footer {
  height: 200px;
  background: #739328;
}

.headerinfo {
  right: 5%;
  margin-right: 5%;
  height: 100px;
  line-height: 100px;
  font-size: 20px;
}

.headerinfo a {
  text-decoration: none;
}

#logininfo {
  margin-top: 40px;
  height: 300px;
}

#logo {
  margin-left: 40px;
  height: 100px;
  width: 150px;
}

#logo img {
  width: 100%;
  height: 100%;
}

.el-aside {
  background-color: #D3DCE6;
  color: #333;
  text-align: center;
  line-height: 700px;
}

.el-main {
  display: flex;
  justify-content: center;
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
  line-height: 700px;
}

.el-container {
  height: 800px;
}

.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}

.custom-indicators {
  display: flex;
  justify-content: center;
  margin-top: 50px;
}

.indicator {
  width: 300px;
  background-color: #999;
  margin: 0 5px;
  cursor: pointer;
  border-radius: 2px;
  transition: background-color 0.3s;
}

.indicator.active {
  background-color: #409EFF;
}
</style>